package com.nefu.softlab.xjwc.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiXiwen
 * @date 2020/2/7 19:36
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String getJsonString(Object object) {
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            System.out.println(e.getLocalizedMessage());
        }
        return jsonString;
    }

    public static Map<String, Object> getMapFromJson(String jsonString) {

        Map<String, Object> rtv = getObjFromJson(jsonString, Map.class);

        if (null == rtv) {
            rtv = new HashMap<>(0);
        }

        return rtv;
    }

    public static List getListFromJson(String jsonString) {
        List<String> rtv = getObjFromJson(jsonString, List.class);
        if (null == rtv) {
            rtv = new ArrayList();
        }
        return rtv;
    }

    private static <T> T getObjFromJson(String jsonString, Class<T> valueType) {
        T rtv = null;
        try {
            rtv = objectMapper.readValue(jsonString, valueType);
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
        }
        return rtv;
    }

    public static void main(String[] args) {
        List<Map<String, Object>> list1 = JsonUtil.getListFromJson("[{\"index\":0,\"lname\":\"11\",\"value\":23,\"part\":0.5},{\"index\":1,\"lname\":\"22\",\"value\":32,\"part\":0.5}]");
        list1.parallelStream().forEach(stringObjectMap -> {
            System.out.println(getJsonString(stringObjectMap));
        });
    }

}
